/**
 * Created by Eric Li on 2015/6/18.
 * 展示任务交办卡详细信息，可以向后台提交信息
 */
(function () {
    var sxfp = function (config) {
        this._config = config;
        this._type = this.getConfig("type");//流程总类型
        this._id = this.getConfig("id");//公文id
        this._taskId = this.getConfig("taskId");//任务id
        this._businessType = this.getConfig("businessType");//流程子类型
        this._buttonFlag = this.getConfig("buttonFlag") || false;//是否显示操作按钮
        this._taskName = this.getConfig("taskName");//流程名称
        this._url = this.getConfig("url") || "";//任务交办卡
        this._format = d3.time.format("%Y -%_m -%_d");//格式化时间
        this._from = this.getConfig("from");
        this._screenindex = this.getConfig("screenindex"); //上一步页面来源 1 待办 2 通知 3 应用 4 账户
    };
    if (typeof (Clickmed) === "undefined") {
        Clickmed = {};
    }
    Clickmed.sxfp = sxfp;
    sxfp.prototype.init = function () {
        var me = this;
        //console.log(me);
        var url = serverURL + "cmcp/phone/doGetLanguages";
        PostCP(url, null, function (dat) {
            me.languages = dat;
        });
        if (me._businessType == "0042") {
            me.wcbb();  // 任务交办卡
            return;
        }

    };
    sxfp.prototype.meet = function (flag) {
        var me = this;
        var render = this._config.render || d3.select("body");
        var d1 = this._config.body || d3.select("body");
        var width = this.width;
        var scrol = d1.append("div").classed("scrol", true).style({
            width: "100%",
            height: "100%",
            position: "absolute",
            background: "#fff",
            left: "0px",
            top: "0px",
            "z-index": 99,
            top: "0px"
        }).attr("id", "scrol");

        var warp = scrol.append("div").classed("dt_warp", true).style({
            position: "relative"
        });
        var datong_header = warp.append("div").classed("datong_header", true);

        var go_back = datong_header.append("div").classed("go_back", true);
        go_back.html("<i><img src =../../common/page/images/go_back_ico.png width =16 height=auto></i>返回");
        go_back.on(touch_s, function () {
            $(this).css("background-color", "#005ebf");
        });
        go_back.on(touch_e, function () {
            $(this).css("background-color", "");


            setTimeout(function () {
                d3.selectAll("#scrol").remove();
                Android.back = TempFunction.back;
            }, Transiacion);

        });
        function back1() {

            setTimeout(function () {
                d3.selectAll("#scrol").remove();
            }, Transiacion);
            Android.back = TempFunction.back;
        }

        // Android返回键动作
        Android.back = TempFunction.back1 = back1;
        datong_header.append("h1").html(me._taskName || "");
        return;
    };
    //获取 url里的type
    sxfp.prototype.getType = function (Type) {
        var me = this;
        var url = me._url;
        if (url.split("?").length > 1) {
            var prame = url.split("?")[1];
            var prames = prame.split("&");
            for (var i = 0; i < prames.length; i++) {
                var targetStep = prames[i].split("=")[0];
                if (targetStep == Type && prames[i].split("=").length > 1) {
                    return prames[i].split("=")[1];
                }
            }
        }

    };
    // 任务交办卡
    sxfp.prototype.wcbb = function () {
        var me = this;
        me.meet(true);
        var url = serverURL + "cmcp/taskassign/getTaskAssign";
        window.plugins.getIntent.show(["OA", "正在获取数据."]);
        var self = {
        	taskId: me._id
        };
        PostCP(url, self, function (dat) {
            if (!dat) {
                Alert("获取数据失败..");
                return
            }
            //console.log(dat);
            me.wcbbData = dat;
            var wcURL = me._url;
            var buttonURL = serverURL + "cmcp/taskassign/getTaskAssignBtns";
            var self = {
            	taskId: me._id
            }
            PostCP(buttonURL, self, function (but) {
               // console.log("获取的按钮:"+JSON.stringify(but))
                me.button = but;
                me.showWcbb();
            }, function () {
            });
        }, function () {
            window.plugins.getIntent.hide();
            Alert("获取数据失败");
        });
    };
    //展示任务交办卡信息
    sxfp.prototype.showWcbb = function () {
        var me = this;
        var wcbbData = me.wcbbData;
        var warp = d3.select("#scrol .dt_warp");
        var disTant = 100;
        if (me._buttonFlag)
            disTant = 44;
        var scrol_ = warp.append("div").classed("scrol_", true).style({
            width: "100%",
            height: height - disTant + "px",
            postion: "relative",
            overflow: "hidden"
        }).attr("id", "scrol_");
        var datong_con = scrol_.append("div").classed("datong_con datong_con_re", true);
        var datong_con = datong_con.append("div").classed("phone_cotent", true);
        var ul = datong_con.append("ul");
        var li = ul.append("li").classed("b_btm", true).style({
            width: "100%"
        });
        var table = li.append("table").attr("cellpadding", "0").attr('cellspacing', "0").style({
            width: "100%"
        });
        //console.log("任务交办卡详情页："+JSON.stringify(wcbbData))
        for (var mn in wcbbData) {
            if (!wcbbData[mn])
                continue;
            if (mn == "superCode") {
                var tr = table.append("tr");
                tr.append("td").html("<div>编&nbsp; 号</div>").style("width", "25%");
                tr.append("td").style("width", "75%").append("div").html(wcbbData[mn].replace(/\n/g, "<br>")).classed("extend", true);
            }
            if (mn == "startDate") {
                var tr = table.append("tr");
                tr.append("td").html("<div>创&nbsp;建&nbsp;日&nbsp;期</div>").style("width", "25%");
                tr.append("td").style("width", "75%").append("div").html(me._format(new Date(wcbbData[mn]))).classed("extend", true)
            }
            if (mn == "endDate") {
                var tr = table.append("tr");
                tr.append("td").html("<div>办&nbsp;结&nbsp;日&nbsp;期</div>").style("width", "25%");
                tr.append("td").style("width", "75%").append("div").html(me._format(new Date(wcbbData[mn]))).classed("extend", true)
            }
            if (mn == "taskContext") {
                var tr = table.append("tr");
                tr.append("td").html("<div>事&nbsp;项&nbsp;内&nbsp;容</div>").style("width", "25%");
                tr.append("td").style("width", "75%").append("div").html(wcbbData[mn].replace(/\n/g, "<br>")).classed("extend", true);
            }
            if (mn == "feedback") {
                var tr = table.append("tr");
                tr.append("td").html("<div>办&nbsp;理&nbsp;人&nbsp;反&nbsp;馈</div>").style("width", "25%");
                tr.append("td").style("width", "75%").append("div").html(wcbbData[mn].replace(/\n/g, "<br>")).classed("extend", true);
            }

            if (mn == "files") {
              var fileList = datong_con.append("div").classed("report_title", true).html("附件:");
              var contentT =wcbbData[mn];
              for (var i = 0; i < contentT.length; i++) {
                  if (!contentT[i]["name"])
                      continue;
                  var newDiv = datong_con.append("div").classed("newDiv", true)
                      .attr("url", contentT[i]["pdfUrl"]).attr("fileName", contentT[i]["name"]);
                  var len = contentT[i]["pdfUrl"].split(".").length;
                  var extend = contentT[i]["pdfUrl"].split(".")[len - 1];
                  var img = newDiv.append("img").attr("src", "../../common/page/images/" + extend + ".png").attr({
                      width: "25",
                      height: "22"

                  }).style("margin-left", "15px");
                  var gragh = newDiv.append("p").html(contentT[i]["name"])
                      .attr("url", contentT[i]["pdfUrl"]).attr("fileName", contentT[i]["name"]);
                  // 打开正文附件
                  newDiv.on("click", function () {
                      if (Flag)
                          return;
                      Flag = true;
                      setTimeout(function () {
                          Flag = false;
                      }, 500);
                      var url = $(this).attr("url");
                      var fileName = $(this).attr("fileName");
                      url = serverURL + url.substr(1);
                      //  Alert(url);
                      window.openF(url, fileName);
                  });
              }
            }
            
            $("tr").each(function () {
                var me = d3.select(this);
                me.select("td")[0][0].style.color = "#2875c3";
            });

        }
        if (!me._buttonFlag) {
            me.wcButton();
        }
        new iScroll("scrol_", {hScrollbar: false, vScrollbar: false});
    };
    //任务交办卡操作按钮
    sxfp.prototype.wcButton = function () {
        var me = this;
        var warp = d3.select("#scrol .dt_warp");
        $(".tj_button2 p input").remove();
        var button = warp.append("div").classed("tj_button2", true).classed("qb_btn_bg", true);
        var tj_button = button.append("p").style({
            "text-align": "center"
        });
        for (var i = 0; i < me.button.length; i++) {
            var Action = me.button[i]["btnName"] || "";
            var input = null;
            if (Action.indexOf("退回") > -1) {
                input = tj_button.append("input").classed("btn_back", true)
                    .attr("type", "button")
                    .attr("value", "退 回");
            } else if (Action.indexOf("作废") > -1) {
                input = tj_button.append("input").classed("drop", true)
                    .attr("value", "作 废")
                    .attr("type", "button")
            }
            else if (Action.indexOf("批示") > -1) {
                input = tj_button.append("input").classed("btn_agree", true)
                    .attr("type", "button")
                    .attr("value", Action);
            } else {
                input = tj_button.append("input").classed("other", true)
                    .attr("type", "button")
                    .attr("value", Action);
            }
            $(input.node()).data("Info", me.button[i])//.attr("disabled", "disabled");

        }
        if ($(".tj_button2 p input").length <= 0) {
            $(".tj_button2").remove();
            $("#scrol_").css({
                height: height - 44 + "px"
            });
        }
        if ($(".tj_button2 p input").length <= 2) {
            $(".tj_button2 p input").css({
                width: "40%"
            });
        }
        if ($(".tj_button2 p input").length === 3) {
            $(".tj_button2 p input").css({
                width: "26.1%"
            });
        }
        if ($(".tj_button2 p input").length === 4) {
            $(".tj_button2 p input").css({
                width: "20%"
            });
        }
        me.wcButtonClick();
    };
    // 任务交办卡 按钮点击事件
    sxfp.prototype.wcButtonClick = function () {
        var me = this;
        $(".tj_button2 p input").on("click", function () {
            if (Flag)
                return;
            Flag = true;
            setTimeout(function () {
                Flag = false;
            }, 500);
            var Info = $(this).data("Info");
            me._Info = Info;
            me.nowStep = Info["nowStep"] || "";
            //me.btnParam = Info["btnParam"] || "";
            me.btnCode = Info["btnCode"] || ""
            me.roleCode = Info["roleCode"] || "";
            //me.type = Info["type"] || "";
            me.btnRoles = Info["btnRoles"] || "";
            me.btnName = Info["btnName"] || ""
            if (me.nowStep == "leader") {
                if (me.btnCode == "approval") {
                    me.nextWithWordAndPerson();
                }else {
                    me.nextWithWord(true);
                }
            } else {
                me.nextWithWord(true);
            }

        });
    };
    // 审批 ，需要输入意见，且需要选择下一位
    sxfp.prototype.nextWithWordAndPerson = function () {
        var me = this;
        var d1 = this._config.body || d3.select("body");
        var select = d3.select("body").append("div").classed("select", true).style({
            width: "100%",
            height: "100%",
            background: "#fff",
            position: "absolute",
            left: "0px",
            top: "0px",
            "z-index": 1000,
            "over-follow": "hidden"
        });

        var dt_warp = select.append("div").classed("dt_warp", true);
        var head = dt_warp.append("div").classed("datong_header", true);

        var back = head.append("div").classed("go_back", true);
        back.html("<i><img src =../../common/page/images/go_back_ico.png width =16 height=auto></i>返回");
        back.on(touch_s, function () {
            $(this).css("background-color", "#005ebf");
        });
        // 左上角返回按钮 动作
        back.on(touch_e, function () {
            $(this).css("background-color", "");

            setTimeout(function () {
                select.remove();
                // Android返回键动作更改
                Android.back = TempFunction.back1;
            }, 10);
        });
        var datong_con = dt_warp.append("div").classed("datong_con", true).style({
            height: (height - 64) + "px",
            background: "#fff"
        });
        var ps_con = datong_con.append("div").classed("ps_con", true);
        var tj_select = ps_con.append("div").classed("tj_select", true).style({
        });
        var tj_con = tj_select.append("div").classed("div_input div_input2", true);
        var label = tj_con.append("label");
        var textarea = $("<textarea></textarea>").attr("rows", "5");
        $(tj_con.node()).append(textarea);
        var commonLanguage = label.append("button").classed("commonLanguage", true).style({
        }).html("常用语句");
        commonLanguage.on(touch_e, function () {
            if ($(this).css("opacity") == "0")
                return;
            if (Flag)
                return;

            Flag = true;
            setTimeout(function () {
                Flag = false;
            }, 500);
            me.Language();
        });
        datong_con.append("div").classed("report_title", true).html("选择签批人").style({
            "text-align": "center"
        });
        var dist = 285;
        var list = datong_con.append("div").classed("list", true).style({
            width: "100%",
            height: (height - dist) + "px",
            "over-follow": "hidden",
            "margin": "0 auto"
        }).attr("id", "list");
        var table = list.append("div").style({
            display: "table",
            width: "100%"
        }).attr("cellpadding", "0").attr("cellspacing", "0");
        listTable(table); // 选择人员列表

        function listTable(table) {
            var menber = me.btnRoles
           // console.log(menber);
            var tr1 = table.append("div").classed("sjr_name", true);
            var ul = tr1.append("ul");
            for (var party in menber) {
                var li = ul.append("li").attr("action", menber[party]["action"])
                    .attr("roleCode", menber[party]['roleCode']).attr("userName", menber[party]["roleName"]);
                li.html("<i class= choose_ico></i>" + menber[party]["roleName"]);
                li.on("click", function () {

                    if (Flag)
                        return;
                    Flag = true;
                    setTimeout(function () {
                        Flag = false;
                    }, 500);
                    if (!$(this).hasClass("sel1")) {
                        $(this).addClass("sel1");
                        d3.select(this).select("i").classed("choosed_ico", true).classed("choose_ico", false);
                        //choosedRoleIds.push($(this).attr("roleCode"));
                    }
                    else {
                        $(this).removeClass("sel1");
                        d3.select(this).select("i").classed("choose_ico", true).classed("choosed_ico", false);
                        //choosedRoleIds.remove($(this).attr("roleCode"));
                    }
                    
                    
//                    $("li").removeClass("sel1");
//                    $(this).addClass("sel1");
//                    d3.selectAll("i").classed("choosed_ico", false).classed("choose_ico", true);
//                    d3.select(this).select("i").classed("choosed_ico", true).classed("choose_ico", false);
//                    me.roleCode = $(this).attr("roleCode");
                });
            }
        };
        var tj_button = datong_con.append("div").classed("tj_button2", true).classed("qb_btn_bg", true).style({
            bottom: "0px"
        });
        var cancel = tj_button.append("input").classed("btn_back", true).attr("type", "button")
            .attr("value", "取  消");
        var ensure = tj_button.append("input").classed("btn_agree", true).attr("type", "button")
            .attr("value", "确  认");
        // 点击取消
        cancel.on(touch_e, function () {
            if (Flag)
                return;
            Flag = true;
            setTimeout(function () {
                Flag = false;
            }, 500);
            // 退回到详细页面
            setTimeout(function () {
                select.remove();
                // Android 返回键动作更改
                Android.back = TempFunction.back1;
            }, Transiacion);
        });
        ensure.on(touch_e, function () {
            if (Flag)
                return;
            Flag = true;
            setTimeout(function () {
                Flag = false;
            }, 500);
            if ($(".list .sel1").size() == 0) {
                Prompt("请选择下一位签批人", 1000);
                return;
            }/*else{
            	Prompt($(".list .sel1").size());
            }*/
            me.wcEnsure(true);
        });
        // Android 返回键动作
        function back2() {
            $(".comList").remove();
            $(".mark").remove();

            setTimeout(function () {
                select.remove();
            }, 10);
            Android.back = TempFunction.back1;
        }

        Android.back = TempFunction.back2 = back2;
        new iScroll("list", {hScrollbar: false, vScrollbar: false}); // 滑动效果
    };
    // 任务交办卡，操作按钮
    // wordFlag :true 需要输入意见， false 不需要输入意见
    sxfp.prototype.nextWithWord = function (wordFlag) {
        var me = this;
        if (!wordFlag) {
            /* me.wcEnsure(wordFlag);
             return;*/
            navigator.notification.confirm(me.btnName + "?", showConfirm, 'OA', ['取消', '确定']);
            // 插件 ，原生弹出框
            function showConfirm(but) {
                if (but == 2) {
                    me.wcEnsure(wordFlag);
                }
            }
            return;
        }
        var d1 = this._config.body || d3.select("body");
        var select = d3.select("body").append("div").classed("select", true).style({
            width: "100%",
            height: "100%",
            background: "#fff",
            position: "absolute",
            left: "0px",
            top: "0px",
            "z-index": 1000,
            "over-follow": "hidden"
        });

        var dt_warp = select.append("div").classed("dt_warp", true);
        var head = dt_warp.append("div").classed("datong_header", true);

        var back = head.append("div").classed("go_back", true);
        back.html("<i><img src =../../common/page/images/go_back_ico.png width =16 height=auto></i>返回");
        back.on(touch_s, function () {
            $(this).css("background-color", "#005ebf");
        });
        // 左上角返回按钮 动作
        back.on(touch_e, function () {
            $(this).css("background-color", "");

            setTimeout(function () {
                select.remove();
                // Android返回键动作更改
                Android.back = TempFunction.back1;
            }, 10);
        });
        // Android 返回键动作
        function back2() {
            $(".comList").remove();
            $(".mark").remove();

            setTimeout(function () {
                select.remove();
            }, 10);
            Android.back = TempFunction.back1;
        }

        Android.back = TempFunction.back2 = back2;
        var datong_con = dt_warp.append("div").classed("datong_con", true).style({
            height: (height - 44) + "px",
            background: "#fff"
        });
        var dist = 122
        if (wordFlag) {
            var ps_con = datong_con.append("div").classed("ps_con", true);
            var tj_select = ps_con.append("div").classed("tj_select", true).style({
            });
            var tj_con = tj_select.append("div").classed("div_input div_input2", true);
            var label = tj_con.append("label");
            var textarea = $("<textarea></textarea>").attr("rows", "5");
            $(tj_con.node()).append(textarea);
            var commonLanguage = label.append("button").classed("commonLanguage", true).style({
            }).html("常用语句");
            commonLanguage.on(touch_e, function () {
                if ($(this).css("opacity") == "0")
                    return;
                if (Flag)
                    return;

                Flag = true;
                setTimeout(function () {
                    Flag = false;
                }, 500);
                me.Language();
            });
        }

        var tj_button = datong_con.append("div").classed("tj_button2", true).classed("qb_btn_bg", true).style({
            bottom: "0px"
        });
        var cancel = tj_button.append("input").classed("btn_back", true).attr("type", "button")
            .attr("value", "取  消");
        var ensure = tj_button.append("input").classed("btn_agree", true).attr("type", "button")
            .attr("value", "确  认");
        // 点击取消
        cancel.on(touch_e, function () {
            if (Flag)
                return;
            Flag = true;
            setTimeout(function () {
                Flag = false;
            }, 500);
            // 退回到详细页面

            setTimeout(function () {
                select.remove();
                // Android 返回键动作更改
                Android.back = TempFunction.back1;
            }, Transiacion);
        });
        ensure.on(touch_e, function () {
            if (Flag)
                return;
            Flag = true;
            setTimeout(function () {
                Flag = false;
            }, 500);
            me.wcEnsure(wordFlag);
        });

    };// 向后台提交操作结果
    sxfp.prototype.wcEnsure = function (wordFlag) {
        var me = this;
        var d1 = this._config.body || d3.select("body");
        var render = this._config.render || d3.select("body");
        if (wordFlag) {
            if (!$("textarea").val().length) {
                Prompt("请输入意见", 1000);
                return;
            }
        }


        var url = serverURL + "cmcp/taskassign/btnClickEvents";
        
        $(".list .sel1").each(function(){
        	me.roleCode+=$(this).attr("roleCode")+",";
        })
        if(me.roleCode.endWith(",")){
        	me.roleCode = me.roleCode.substring(0,me.roleCode.length-1);
        }
        var self = {
        	taskId: me._id,
            btnCode: me.btnCode,
            nowStep: me.nowStep,
            roleCode: me.roleCode,
            message: $("textarea").val() || ""
        };
       // console.log(url, self);
        PostCP(url, self, function (dat) {
            if (!dat) {
                Prompt("提交失败");
                return;
            }
            if (dat == "success") {
                Prompt("提交成功")
            } else {
               // console.log(dat);
                Prompt("成功分发给" + dat.split(" ").join("<br>"));
            }

            setTimeout(function () {
                d3.select(".select").remove();
            }, 10);
            setTimeout(function () {
                d3.selectAll("#scrol").remove();
                // Android返回键动作更改并重新刷新待办列表
                window.localStorage.status = "true";
                Android.back = TempFunction.back;
            }, 0);
        }, function () {
            Prompt("提交失败")
        });
    };
    /*************************
     *   以上为任务交办卡增加操作按钮部分
     *
     *
     *
     * */
    sxfp.prototype.getConfig = function (key) {
        if (this._config == null) {
            return null;
        } else {
            if (typeof (this._config[key]) != "undefined") {
                return this._config[key];
            } else {
                return null;
            }
        }
    };

	 // 常用语列表
    sxfp.prototype.Language = function () {
        var me = this;
        var value = $("textarea").val();
        var dat = me.languages;
        if (!dat["languages"] || !dat["languages"].length) {
            Alert("您还没有常用语句，请到后台维护您的常用语");
            return;
        }
        comList = dat["languages"] || comList;
        var List = d3.select("body").append("div").classed("comList", true);
        var head = List.append("div").classed("head", true).html("常用语列表");
        var con = List.append("div").classed("con", true).attr("id", "comList").style({
            "border-radius": "3px",
            background: "#ccdfee"
        });
        var ul = con.append("ul").style("overflow", "hidden").style({
            width: "80%",
            position: "absolute",
            left: "10%"
        });
        ul.append("li").style({
            height: "10px",
            "border-bottom": ".4px solod #838383"
        });
        for (var i = 0; i < comList.length; i++) {
            ul.append("li").html("<img src=../../common/page/images/mr.png>  " + comList[i]);

        }
        ul.append("li").style({
            height: "10px",
            "border-bottom": ".4px solod #838383"
        });
        new iScroll("comList", {hScrollbar: false, vScrollbar: false});
        var html = "";
        $(".comList ul li").each(function () {
            $(this).on("click", function () {
                if (Flag)
                    return;
                Flag = true;
                setTimeout(function () {
                        Flag = false;
                    },
                    500
                )
                $(this).toggleClass("selec");
                var that = d3.select(this);
                if ($(this).hasClass("selec")) {
                    html += $(this).text() + " ";
                    that.select("img").attr("src", "../../common/page/images/xz.png");
                } else {
                    html = html.replace($(this).text() + " ", "");
                    that.select("img").attr("src", "../../common/page/images/mr.png");
                }
                $("textarea").val(value + html);

            });
        });
        var but = List.append("div").classed("but", true);
        var p = but.append("p").style({
            background: '#afbcca'
        });
        var but2 = p.append("button").style({
            width: "100px",
            height: "35px",
            background: "#d76856",
            color: "#ffe",
            "border-radius": "7px",
            "font-size": "18px",
            "margin": "10px"
        }).html("取 消");
        var but1 = p.append("button").style({  // 这里应该把样式写到 css 里
            width: "100px",
            height: "35px",
            border: '0px solid #70ab67',
            background: '#65d756',
            color: "#ffe",
            "border-radius": "7px",
            "font-size": "18px",
            "margin": "10px"
        }).html("确 认");

        but1.on("click", function () {
            Flag = true;
            List.remove();

            setTimeout(function () {
                Flag = false;
            }, 1000);

        });

        but2.on("click", function () {
            Flag = true;
            List.remove();

            $("textarea").val(value);
            setTimeout(function () {
                Flag = false;
            }, 1000);

        });


    };
})();